//
//  RegisterNextViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/9/17.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class RegisterNextStepViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var button: UIButton!
    
    @IBOutlet weak var buttonLayoutConstraint: NSLayoutConstraint!
    
    let userAuthVM = UserAuthViewModel.shared
    
    let disposeBag = DisposeBag()
    
    var totpResult: TOTPAuthResult?
    
    let authManager = AuthManager.share
    
    let backButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "back_black"), for: .normal)
        return button
    }()
    
    let titleLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 24)
        label.textColor = UIColor.gray
        label.text = LanguageHelper.getString(key: "FINISH_REGISTER")
        return label
    }()
    
    let descriptionLabel: UILabel = {
        let label = UILabel()
        label.font = AppFont(size: 14)
        label.textColor = lightTextColor
        label.text = LanguageHelper.getString(key: "REGISTER_USERNAME_PW")
        return label
    }()
    
    let usernameTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "USERNAME")
        textField.font = AppFont(size: 15)
        return textField
    }()
    
    let usernameSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    let passwdTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "PASSWORD")
        textField.font = AppFont(size: 15)
        textField.isSecureTextEntry = true
        return textField
    }()
    
    let passwdSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    let passwdConfirmTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = LanguageHelper.getString(key: "CONFIRM_NEW_PASSWORD")
        textField.font = AppFont(size: 15)
        textField.isSecureTextEntry = true
        return textField
    }()
    
    let passwdConfirmSaperator: UIView = {
        let view = UIView()
        view.backgroundColor = saperatorColor
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        button.layer.cornerRadius = 3
        button.layer.masksToBounds = true
        
        backButton.frame = CGRect(x: 15, y: 35, width: 22, height: 22)
        backButton.addTarget(self, action: #selector(backForButton(_:)), for: .touchUpInside)
        
        let leading: CGFloat = 45
        
        let textMaxSize = CGSize(width: self.view.bounds.width, height: 30)
        let titleSize = TextSize.textSize(text: titleLabel.text!, font: titleLabel.font, maxSize: textMaxSize)
        titleLabel.frame = CGRect(x: leading, y: 85, width: titleSize.width, height: titleSize.height)
        let descriptionSize = TextSize.textSize(text: descriptionLabel.text!, font: descriptionLabel.font, maxSize: textMaxSize)
        descriptionLabel.frame = CGRect(x: leading, y: titleLabel.frame.origin.y + titleLabel.frame.height + 8, width: descriptionSize.width, height: descriptionSize.height)
        
        var currentY = descriptionLabel.frame.origin.y + descriptionLabel.frame.height
        
        usernameTextField.frame = CGRect(x: leading, y: currentY + 30, width: self.view.bounds.width - CGFloat(2) * leading, height: 25)
        
        currentY = usernameTextField.frame.origin.y + usernameTextField.frame.height
        
        usernameSaperator.frame = CGRect(x: leading, y: currentY + 8, width: self.view.bounds.width - CGFloat(2) * leading, height: 0.5)
        
        currentY = usernameSaperator.frame.origin.y + usernameSaperator.frame.height
        
        passwdTextField.frame = CGRect(x: leading, y: currentY + 30, width: self.view.bounds.width - CGFloat(2) * leading, height: 25)
        
        currentY = passwdTextField.frame.origin.y + passwdTextField.frame.height
        
        passwdSaperator.frame = CGRect(x: leading, y: currentY + 8, width: self.view.bounds.width - CGFloat(2) * leading, height: 0.5)
        
        currentY = passwdSaperator.frame.origin.y + passwdSaperator.frame.height
        
        passwdConfirmTextField.frame = CGRect(x: leading, y: currentY + 30, width: self.view.bounds.width - CGFloat(2) * leading, height: 25)
        
        currentY = passwdConfirmTextField.frame.origin.y + passwdConfirmTextField.frame.height
        
        passwdConfirmSaperator.frame = CGRect(x: leading, y: currentY + 8, width: self.view.bounds.width - CGFloat(2) * leading, height: 0.5)
        
        currentY = passwdConfirmSaperator.frame.origin.y + passwdConfirmSaperator.frame.height
        
        buttonLayoutConstraint.constant = currentY + 45
        
        currentY = currentY + 45 + button.frame.height
        
        button.isEnabled = false
        
        self.usernameTextField.delegate = self
        self.passwdTextField.delegate = self
        self.passwdConfirmTextField.delegate = self
        
        self.usernameTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        
        self.passwdTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        
        self.passwdConfirmTextField.addTarget(self, action: #selector(textFieldValueChange(_:)), for: .editingChanged)
        
        button.addTarget(self, action: #selector(register(_:)), for: .touchUpInside)
        
        self.view.addSubview(backButton)
        self.view.addSubview(titleLabel)
        self.view.addSubview(descriptionLabel)
        self.view.addSubview(usernameTextField)
        self.view.addSubview(usernameSaperator)
        self.view.addSubview(passwdTextField)
        self.view.addSubview(passwdSaperator)
        self.view.addSubview(passwdConfirmTextField)
        self.view.addSubview(passwdConfirmSaperator)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self.view)
            if !self.usernameTextField.frame.contains(point) && !self.passwdTextField.frame.contains(point) && !self.passwdConfirmTextField.frame.contains(point) {
                self.usernameTextField.resignFirstResponder()
                self.passwdTextField.resignFirstResponder()
                self.passwdConfirmTextField.resignFirstResponder()
            }
        }
    }
    
    func textFieldValueChange(_ sender: UITextField) {
        if self.usernameTextField.text != "" && self.passwdTextField.text != "" && self.passwdConfirmTextField.text != "" {
            self.button.isEnabled  = true
        } else {
            self.button.isEnabled = false
        }
    }
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField == self.usernameTextField {
            usernameSaperator.backgroundColor = UIColor.black
        } else if textField == self.passwdConfirmTextField {
            passwdConfirmSaperator.backgroundColor = UIColor.black
        } else {
            passwdSaperator.backgroundColor = UIColor.black
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == self.usernameTextField {
            usernameSaperator.backgroundColor = saperatorColor
        } else if textField == self.passwdConfirmTextField {
            passwdConfirmSaperator.backgroundColor = saperatorColor
        } else {
            passwdSaperator.backgroundColor = saperatorColor
        }
    }
    
    func register(_ sender: UIButton) {
        self.usernameTextField.resignFirstResponder()
        self.passwdTextField.resignFirstResponder()
        self.passwdConfirmTextField.resignFirstResponder()
        if passwdTextField.text != passwdConfirmTextField.text {
            self.showPromptView(message: LanguageHelper.getString(key: "PASSWORD_DIFF"), confirmText: LanguageHelper.getString(key: "OK"))
        } else if (passwdTextField.text?.count)! < 4 {
            self.showPromptView(message: LanguageHelper.getString(key: "AT_LEAST4"), confirmText: LanguageHelper.getString(key: "OK"))
        } else {
            let username = usernameTextField.text!.trim()
            let password = passwdTextField.text!.trim()
            let imPassword = password.md5()
            //print("***************jiami PWD:\(imPassword)")
            userAuthVM.register(username: username, password: password, token: (totpResult?.token)!)
                .subscribe(onNext: { response in
                    if let success = response.success {
                        if success {
                            //注册成功
                            self.usernameTextField.resignFirstResponder()
                            self.passwdTextField.resignFirstResponder()
                            if let data = response.data as? UserRegisterResponseData {
                                self.login(username: username, password: imPassword, token: data.token!)
//                                JMSGUser.register(withUsername: username, password: imPassword) { (result, error) in
//                                    let _ = DispatchQueue.main.async {
//                                        MBProgressHUD_JChat.hide(forView: self.view, animated: true)
//                                        if error == nil {
//                                        } else {
//                                            self.showPromptView(message: "註冊失敗，請重試", confirmText: "確認")
//                                        }
//                                    }
//                                }
                            }
                        } else {
                            if let data = response.data as? String {
                                self.showPromptView(message: data, confirmText: LanguageHelper.getString(key: "OK"))
                            } else {
                                self.showPromptView(message: LanguageHelper.getString(key: "UNKNOW"), confirmText: LanguageHelper.getString(key: "OK"))
                            }
                        }
                    }
                })
                .addDisposableTo(disposeBag)
        }
        
    }
    
    func login(username: String, password: String, token: String) {
        JMSGUser.login(withUsername: username, password: password) { [unowned self] (result, error) in
            if error == nil {
                UserDefaults.standard.set(username, forKey: kLastUserName)
                UserDefaults.standard.set(username, forKey: kCurrentUserName)
                UserDefaults.standard.set(password, forKey: kCurrentUserPassword)
                self.authManager.login(token: token)
                self.dismiss(animated: true, completion: nil)
            } else {
                self.showPromptView(message: LanguageHelper.getString(key: "REGISTERED_NOT_LOGIN"), confirmText: LanguageHelper.getString(key: "OK"))
            }
        }
    }
}
